#include <QProgressDialog>

#include "medianfilter.h"

MedianFilter::MedianFilter()
    : Filter()
{
}

MedianFilter::MedianFilter(int size)
    : Filter(size)
{
}

MedianFilter::MedianFilter(int size, QProgressDialog *progressDialog)
    : Filter(size, progressDialog)
{
}


int MedianFilter::median(QList<int> list)
{
    int N = list.size();
    qSort(list);
    if (N % 2 == 0)
        return (list[N / 2 - 1] + list[N / 2]) / 2;
    return list[N / 2];
}

QImage MedianFilter::filter(const QImage &I)
{
    if (m < 1)
        return I;

    QVector<QRgb> colors(256);
    for (int i = 0; i < 256; i++)
        colors.replace(i, qRgb(i,i,i));
    QImage Im(I.size(), QImage::Format_Indexed8);
    Im.setColorTable(colors);

    for (int i = 0; i < I.height(); i++) {
        if (progress(i)) break;
        for (int j = 0; j < I.width(); j++) {
            QList<int> neighborhood;
            for (int h = -m/2; h <= m/2; h++)
                for (int k = -m/2; k <= m/2; k++) {
                    int y = i + h;
                    if (y < 0) y = 0;
                    if (y >= Im.height()) y = Im.height() - 1;
                    int x = j + k;
                    if (x < 0) x = 0;
                    if (x >= Im.width()) x = Im.width() - 1;
                    neighborhood << qGray(I.pixel(x, y));
                }
            Im.setPixel(j, i, median(neighborhood));
        }
    }
    return Im;
}
